package controllers

import (
	"beego_project/models"
	"beego_project/syserror"
	"github.com/astaxie/beego"
	"github.com/pkg/errors"
	"github.com/satori/go.uuid"
)

type BaseController struct {
	beego.Controller
	User    models.User
	IsLogin bool
}

const SESSION_USER_KEY = "SESSION_USER_KEY"

// 通用接口
type NextPreparer interface {
	NextPrepare()
}

func (this *BaseController) Prepare() {
	this.Data["Path"] = this.Ctx.Request.RequestURI
	u, ok := this.GetSession(SESSION_USER_KEY).(models.User)
	if ok {
		this.User = u
		this.IsLogin = true
		this.Data["User"] = u
	}
	this.Data["isLogin"] = this.IsLogin

	if a, ok := this.AppController.(NextPreparer); ok {
		a.NextPrepare()
	}
}

func (this *BaseController) Abort500(err error) {
	this.Data["error"] = err
	this.Abort("500")
}

func (this *BaseController) Abort404() {
	this.Abort("404")
}

func (this *BaseController) GetMustString(key, msg string) string {
	// str
	str := this.GetString(key)
	if len(str) == 0 {
		this.Abort500(errors.New(msg))
	}
	return str
}

func (this *BaseController) MustLogin() {
	if !this.IsLogin {
		this.Abort500(&syserror.NoUserError{})
	}
}

// 封装回调
type H map[string]interface{}

func (this *BaseController) JSONOK(msg, action string) {
	this.Data["json"] = H{
		"code":   0,
		"msg":    msg,
		"action": action,
	}
	this.ServeJSON()
}

func (this *BaseController) JSONOKH(msg string, data H) {
	data["code"] = 0
	data["msg"] = msg
	this.Data["json"] = data
	this.ServeJSON()
}

// 获取uuid
func (this *BaseController) UUID() string {

	u, err := uuid.NewV4()
	if err != nil {
		this.Abort500(syserror.New("系统错误", err))
	}
	return u.String()
}
